package com.mingtu.guards.activity;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceClient;
import com.amap.api.fence.GeoFenceListener;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.amap.api.maps.offlinemap.OfflineMapCity;
import com.amap.api.maps.offlinemap.OfflineMapManager;
import com.amap.api.trace.LBSTraceClient;
import com.amap.api.trace.TraceLocation;
import com.amap.api.trace.TraceStatusListener;
import com.amap.api.track.AMapTrackClient;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dinuscxj.progressbar.CircleProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzf.easyfloat.EasyFloat;
import com.lzf.easyfloat.enums.ShowPattern;
import com.lzf.easyfloat.enums.SidePattern;
import com.lzf.easyfloat.interfaces.OnFloatCallbacks;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.task.XExecutor;
import com.mingtu.center.activity.MyOffLineMapActivity;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.bean.UserInfoBean;
import com.mingtu.common.callback.ResultCallback;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.gpsstatus.GpsStatusImageView;
import com.mingtu.common.gpsstatus.GpsStatusProxy;
import com.mingtu.common.gpsstatus.GpsStatusTextView;
import com.mingtu.common.room.TrackHistoryEvent;
import com.mingtu.common.room.TrackHistoryEventDao;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.GPSTransToAMap;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.NotificationUtils;
import com.mingtu.common.utils.PathSmoothTool;
import com.mingtu.common.utils.PlayMusicUtils;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.ScreenUtils;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.common.utils.TimeUtils;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.guards.R;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.GeoFenceBean;
import com.mingtu.guards.bean.MenuDeviceBean;
import com.mingtu.guards.bean.MenuNurseryBean;
import com.mingtu.guards.bean.MenuProtectBean;
import com.mingtu.guards.bean.MenuTrackBean;
import com.mingtu.guards.bean.MenuTreeBean;
import com.mingtu.guards.bean.ResAreaBean;
import com.mingtu.guards.callback.MyStringDialogCallback;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.utils.MySPTools;
import com.mingtu.guards.utils.TileUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.mingtu.common.utils.Constant.GEOFENCE_BROADCAST_ACTION;
import static com.mingtu.common.utils.MyUtills.getBounds;
import static com.mingtu.guards.utils.MyConstant.LEFT_TOP_LOCATION;
import static com.mingtu.guards.utils.MyConstant.MAP_INDEX;
import static com.mingtu.guards.utils.MyConstant.MAX_ZOOM;
import static com.mingtu.guards.utils.MyConstant.MIN_ZOOM;
import static com.mingtu.guards.utils.MyConstant.RIGHT_BOTTOM_LOCATION;

public class TrackActivity extends MyBaseActivity implements
        LocationSource, AMapLocationListener,
        TraceStatusListener, AMap.OnMarkerClickListener,
        AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener,
        OfflineMapManager.OfflineLoadedListener,
        GeoFenceListener, XExecutor.OnAllTaskEndListener {

    @BindView(R.id.iv_location)
    ImageView ivLocation;

    @BindView(R.id.iv_switch)
    ImageView ivSwitch;

    //    @BindView(R.id.iv_upload_location)
//    ImageView ivUploadLocation;
    @BindView(R.id.layout_bottom_mileage)
    FrameLayout layoutBottomMileage;
    @BindView(R.id.iv_start)
    ImageView ivStart;

    @BindView(R.id.tv_set_interest)
    TextView tvSetInterest;
    @BindView(R.id.tv_top_tip)
    TextView tvTopTip;
    @BindView(R.id.edit_interest)
    EditText editInterest;
    @BindView(R.id.layout_pop_edit)
    RelativeLayout layoutPopEdit;
    @BindView(R.id.tv_sure_pop)
    TextView tvSurePop;
    @BindView(R.id.tv_cancle_pop)
    TextView tvCanclePop;
    @BindView(R.id.tv_mileage)
    TextView tvMileage;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_reset_track)
    TextView tvResetTrack;
    @BindView(R.id.tv_continue_track)
    TextView tvContinueTrack;
    @BindView(R.id.layout_pop_tips)
    RelativeLayout layoutPopTips;
    @BindView(R.id.gpsImage)
    GpsStatusImageView gpsImage;
    @BindView(R.id.circle_progress)
    CircleProgressBar circleProgress;
    @BindView(R.id.tv_end_long)
    TextView tvEndLong;
    @BindView(R.id.tv_top_tip2)
    TextView tvTopTip2;
    @BindView(R.id.iv_close_pop)
    ImageView ivClosePop;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.gpsText)
    GpsStatusTextView gpsText;
    @BindView(R.id.iv_collect)
    CheckBox ivCollect;
    private MapView mapView;
    private Unbinder unbinder;
    private AMap aMap;
    private AMapLocationClient locationClient = null;
    private int locationNum = 0;
    private LatLng location;
    private AMapTrackClient aMapTrackClient;
    private boolean isServiceRunning;
    private boolean uploadToTrack = true;
    private boolean isGatherRunning = true;
    private long terminalId;
    private final String TAG = "tab1page";
    private static final String CHANNEL_ID_SERVICE_RUNNING = "CHANNEL_ID_SERVICE_RUNNING";
    private List<Polyline> polylines = new CopyOnWriteArrayList<>();
    private List<Polyline> historyPolylines = new CopyOnWriteArrayList<>();
    private List<Marker> endMarkers = new CopyOnWriteArrayList<>();
    private long trackId;
    public static String TERMINAL_NAME;
    public static long SERVICE_ID = 0;
    private View layout;
    private OnLocationChangedListener mListener;
    private MarkerOptions markerOptionsIntetest;
    private Marker markerInterest;
    private BitmapDescriptor iconInterest;
    private double latInterest;
    private double lngInterest;
    private String interestName;
    private List<LatLng> mOriginList = new ArrayList<>();
    private boolean trackFlag = false;
    private Polyline mapPolyline;
    private TimeUtils timeUtils;
    private List<LatLng> myLatLngList = new ArrayList<>();
    //    private List<Marker> markerList = new ArrayList<>();
//    private List<Polyline> polylineList = new ArrayList<>();
//    private LinkedHashMap<Object, String> locationInfoMap = new LinkedHashMap<>(); // LatLng 为键   time为值
    private LinkedHashMap<String, Object> locationInfoMap = new LinkedHashMap<>(); // time为键 LatLng为值
    private Marker startMarker;
    private long timeStampStart;
    private long timeStampEnd;
    private List<Marker> treeMarkers = new CopyOnWriteArrayList<>();
    private List<Marker> protectMarkers = new CopyOnWriteArrayList<>();
    private List<Marker> equipmentMarkers = new CopyOnWriteArrayList<>();
    private List<Marker> locationMarkers = new CopyOnWriteArrayList<>();

    private List<MenuTrackBean.FeaturesBean> DataBean = new ArrayList<>();
    private List<Marker> trackMarkers;
    private List<Polyline> trackPolylineList;
    private List<MenuTrackBean.FeaturesBean> featuresBeans;
    private List<List<LatLng>> latLngsList;
    private List<Polygon> trackPolygonList = new CopyOnWriteArrayList<>();
    private List<Polygon> nuseryPolygonList = new CopyOnWriteArrayList<>();
    private List<Marker> deviceMarker;
    private LBSTraceClient traceClient;
    private PathSmoothTool mpathSmoothTool;
    private LocationManager locationManager;
    private GpsStatusProxy proxy;
    private long locationTime;
    private MyLocationStyle myLocationStyle;
    private List<LatLng> optimizeLatLng = new ArrayList<>();
    private HashMap<String, Object> locationHashMap;
    private int GPS_REQUEST_CODE = 0x11;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private View infoWindow;
    private GeoFenceClient mGeoFenceClient;
    private boolean GeoFenceStatus = true;//默认在地里围栏里面
    private List<Polygon> fencePolygonList = new CopyOnWriteArrayList<>();
    private ValueAnimator animator;
    private Vibrator vibrator;
    private TileOverlay tileOverlay;
    private String[] tipArray = {"您正在使用离线地图", "您正在使用移动网络，请注意流量使用情况"};
    private OfflineMapManager offlineMapManager;
    private String locationCity;
    private int locationCityNum = 0; //定位的城市获取的次数，防止重复的初始化
    private ArrayList<HashMap<String, Object>> uploadLocationList = new ArrayList<>(); //上报地点的时间和坐标  时间是键  坐标是值  用于结束的时候用
    private ArrayList<HashMap<String, Object>> myUploadLocationList = new ArrayList<>(); //上报地点的时间和坐标 用于重新获取数据用
    private float toatalDistance = 0;
    private long start;
    private Marker locMarker;
    private Circle ac;
    private Circle c;
    private BroadcastReceiver mScreenBroadcastReceiver;
    private Bitmap bitmap;
    public final String SD_APP_DIR_NAME = Constant.SD_APP_DIR_NAME; //存储程序在外部SD卡上的根目录的名字
    private final String File_Directory = TileUtils.File_Directory;
    private TileOverlayOptions tileOverlayOptions;
    private OkDownload okDownload;
    private boolean isSports = false;
    private SensorManager sensorManager;
    private float maxSensorValue;
    private AMapLocation myAMapLocation;
    private NotificationManager notificationManager;
    private BasePopupView popupView;
    private List<HashMap<String, String>> myTestList;
    private HashMap<String, Object> myTestHashMap;
    private List<LatLng> areaAllLatLng;
    //    @SuppressLint("InvalidWakeLockTag")
//    private PowerManager.WakeLock wakeLock;
    private boolean isSwitch = true;
    private ImmersionBar immersionBar;
    private long firstPressedTime;
    private BasePopupView netPopupView;
    private TrackHistoryEventDao trackHistoryEventDao;

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        initMap();
        initAMapGeoFence();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_track;
    }

    @Override
    protected void initData() {
        String serviceId = SPStaticUtils.getString(SPTools.serviceSid);
        String serviceName = SPStaticUtils.getString(SPTools.serviceName);
        if (!StringUtils.isEmpty(serviceId)) {
            SERVICE_ID = Long.parseLong(serviceId);
        }
        if (!StringUtils.isEmpty(serviceName)) {
            TERMINAL_NAME = serviceName;
        }

        ivCollect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //打开设置兴趣视图
                    int visibility = layoutBottomMileage.getVisibility();
                    if (visibility == 0) { //0 的时候显示巡护的视图打开此时不能设置兴趣点
                        ToastUtils.showLong("请先结束巡护！");
                        ivCollect.setChecked(false);
                    } else {
                        ivCollect.setChecked(true);
                        ivStart.setVisibility(View.GONE);
                        tvSetInterest.setVisibility(View.VISIBLE);
                        tvTopTip.setVisibility(View.VISIBLE);
//                        ivUploadLocation.setVisibility(View.VISIBLE);
                        initInterest();
                        if (markerInterest != null) {
                            markerInterest.setVisible(true);
                        }
                    }

                } else {
                    ivCollect.setChecked(false);
                    //关闭设置兴趣点视图
                    ivStart.setVisibility(View.VISIBLE);
                    tvSetInterest.setVisibility(View.GONE);
                    tvTopTip.setVisibility(View.GONE);
//                    ivUploadLocation.setVisibility(View.GONE);
                    if (markerInterest != null) {
                        markerInterest.setVisible(false);
                    }
                }
            }
        });


        EventBus.getDefault().register(this);


        //获取系统的Vibrator服务
        vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);

//        //图层的范围值
        String XYZOOM_LEFTTOP = SPStaticUtils.getString(MySPTools.XYZOOM_LEFTTOP);
        String XYZOOM_RIGHTBOTTOM = SPStaticUtils.getString(MySPTools.XYZOOM_RIGHTBOTTOM);
        String MyXYZOOM = SPStaticUtils.getString(MySPTools.XYZOOM);
        if (MyXYZOOM.contains(XYZOOM_LEFTTOP) && MyXYZOOM.contains(XYZOOM_RIGHTBOTTOM)) {
            //下面的逻辑是为了处理初始值为""的情况
            if (StringUtils.isEmpty(XYZOOM_LEFTTOP) && StringUtils.isEmpty(XYZOOM_RIGHTBOTTOM)) {
                new TileTask().execute();
            }
        } else {
            new TileTask().execute();
        }


        initAnimator();

    }


    @Override
    protected void initView() {

        hideHeadView();
        StatusBarUtil.addStatusBarHeight(statusBarView);
        //沉侵式状态栏
        immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
        immersionBar.navigationBarDarkIcon(false);
        immersionBar.init();


        iconInterest = BitmapDescriptorFactory.fromResource(R.mipmap.icon_gps_xqd); //兴趣点的覆盖物
        trackHistoryEventDao = BaseApplication.getBaseApplication().getTrackHistoryEventDao();

        String myTrackFlag = SPStaticUtils.getString(SPTools.trackFlag);
        List<TrackHistoryEvent> trackHistoryEvents = trackHistoryEventDao.getAll();

        //巡护开始 并且巡护的历史轨迹不为空的情况下显示弹框
        MyLogUtil.e("TrackFlag", "initView===myTrackFlag==" + myTrackFlag);

        if (!StringUtils.isEmpty(myTrackFlag) && trackHistoryEvents.size() > 0) {
            if (myTrackFlag.equals("true")) {
                layoutPopTips.setVisibility(View.VISIBLE);
            } else if (myTrackFlag.equals("false")) {
                layoutPopTips.setVisibility(View.GONE);
            }
        } else {
            layoutPopTips.setVisibility(View.GONE);
        }

        //为了适配android11，这个权限单独申请。如果申请的权限中包含后台定位权限， 那么这里面则不能包含和定位无关的权限，否则框架会抛出异常，
        // 因为 ACCESS_BACKGROUND_LOCATION 和其他非定位权限定位掺和在一起申请，在 Android 11 上会出现不申请直接被拒绝的情况。
        //也就是说，如果你想获得后台定位权限，必须弹窗两次：
        //第一次，申请普通定位权限的弹窗。
        //第二次，在用户同意了普通定位权限之后，申请 后台定位权限时弹窗。
        //这里也要千万注意，在没有拿到 普通定位权限的时候，直接申请后台定位权限，将不弹窗直接授权失败。

        XXPermissions.with(this)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.NOTIFICATION_SERVICE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (permissions.contains(Permission.ACCESS_COARSE_LOCATION) || permissions.contains(Permission.ACCESS_FINE_LOCATION)) {
                            initGpsStatus();
                            if (myAMapLocation != null && mListener != null) { //防止点击定位按钮的时候不出现小蓝点
                                mListener.onLocationChanged(myAMapLocation);// 显示系统小蓝点
                                aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                            } else {
                                aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                            }
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            new XPopup.Builder(TrackActivity.this)
                                    .isDestroyOnDismiss(true)
                                    .dismissOnTouchOutside(true)
                                    .hasShadowBg(true)
                                    .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_location_auth),
                                            context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                            new OnConfirmListener() {
                                                @Override
                                                public void onConfirm() {
                                                    XXPermissions.startPermissionActivity(TrackActivity.this, permissions);
                                                }
                                            }, null, false)
                                    .show();
                        } else {

                        }

                    }
                });


//        initGpsStatus();


        tvEndLong.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent e) {
                // 拦截底部布局的点击事件 返回值为true 消费事件
                switch (e.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        animator.start();
                        if (vibrator != null) {
                            vibrator.vibrate(150);
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        animator.cancel();
                        circleProgress.setProgress(0);
                        break;

                }
                return true;
            }
        });

    }


    @Override
    protected void getData() {

    }


    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        //切入前台后关闭后台定位功能
        if (null != locationClient) {
            locationClient.disableBackgroundLocation(true);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        MyLogUtil.e("tabpage1", "onStop===");
//        boolean isAppForeground = AppUtils.isAppForeground();
        //如果app已经切入到后台，启动后台定位功能
        if (null != locationClient) {
            locationClient.enableBackgroundLocation(NotificationUtils.NOTIFY_ID, NotificationUtils.buildNotification(BaseApplication.getContext()));
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        if (null != locationClient) {
            locationClient.enableBackgroundLocation(NotificationUtils.NOTIFY_ID, NotificationUtils.buildNotification(BaseApplication.getContext()));
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        MyLogUtil.e("tabpage1", "onSaveInstanceState===");
        boolean isScreenLock = ScreenUtils.isScreenLock();
        if (isScreenLock) {
            return; //App如果是锁屏的时候不执行此方法
        }
        trackHistoryEvent(null);
        if (uploadLocationList.size() > 0) {
            //保存上报记录
            for (int i = 0; i < uploadLocationList.size(); i++) {
                HashMap<String, Object> locationInfoMap = uploadLocationList.get(i);
                HashMap<String, Object> hashMap = new HashMap<>();
                for (String key : locationInfoMap.keySet()) {
                    LatLng latLng = (LatLng) locationInfoMap.get(key); //键是时间   值是坐标
                    double lng = latLng.longitude;
                    double lat = latLng.latitude;
                    hashMap.put("latitude", lat + "");
                    hashMap.put("longitude", lng + "");
                    hashMap.put("locationTime", key);
                }
                myUploadLocationList.add(hashMap);
            }


            HashMap<String, Object> map = new HashMap();
            map.put("uploadHistory", myUploadLocationList);
            String uploadHistoryStr = GsonUtils.toJson(map);
            SPStaticUtils.put(SPTools.uploadHistoryStr, uploadHistoryStr);
        }

        //保存巡护的时间
        if (timeUtils != null) {
            long count = timeUtils.getTime();
            SPStaticUtils.put(SPTools.trackTime, count + "");
//            timeUtils.stopTimer();
        }

    }

    @Override
    public void onDestroy() {
        MyLogUtil.e("tabpage1", "onDestroy===");

        trackHistoryEvent(null);

        if (uploadLocationList.size() > 0) {
            //保存上报记录
            for (int i = 0; i < uploadLocationList.size(); i++) {
                HashMap<String, Object> locationInfoMap = uploadLocationList.get(i);
                HashMap<String, Object> hashMap = new HashMap<>();
                for (String key : locationInfoMap.keySet()) {
                    LatLng latLng = (LatLng) locationInfoMap.get(key); //键是时间   值是坐标
                    double lng = latLng.longitude;
                    double lat = latLng.latitude;
                    hashMap.put("latitude", lat + "");
                    hashMap.put("longitude", lng + "");
                    hashMap.put("locationTime", key);
                }
                myUploadLocationList.add(hashMap);
            }


            HashMap<String, Object> map = new HashMap();
            map.put("uploadHistory", myUploadLocationList);
            String uploadHistoryStr = GsonUtils.toJson(map);
            SPStaticUtils.put(SPTools.uploadHistoryStr, uploadHistoryStr);

        }

        //保存巡护的时间
        if (timeUtils != null) {
            long count = timeUtils.getTime();
            SPStaticUtils.put(SPTools.trackTime, count + "");
            timeUtils.stopTimer();
        }

        stopGetDeviceData();

        //销毁时，需要销毁定位client
        if (null != locationClient) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }

        deactivate();

//        if (isServiceRunning) {
//            aMapTrackClient.stopTrack(new TrackParam(SERVICE_ID, terminalId), onTrackListener);
//        }

        if (proxy != null) {
            if (locationManager != null) {
                locationManager.removeUpdates(myLocationListener);
            }
            proxy.unRegister();
        }

        if (mGeoFenceReceiver != null) {
            unregisterReceiver(mGeoFenceReceiver);
        }

        if (mGeoFenceClient != null) {
            //清除围栏
            mGeoFenceClient.removeGeoFence();
        }

        //自定义瓦片
        if (tileOverlay != null) {
            tileOverlayOptions.visible(false);
            tileOverlay.remove();
        }

        EventBus.getDefault().unregister(this);

        removeScreenChangeBroadCast();

        if (okDownload != null) {
            okDownload.removeOnAllTaskEndListener(this);
        }

        if (sensorManager != null) {
            sensorManager.unregisterListener(new MySensorEventListener());
        }

        if (popupView != null) {
            popupView.destroy();
        }

//        if (wakeLock != null) {
//            wakeLock.release();
//        }
//        stopService();

        //销毁地图对象,在此方法之后代码将不再执行
        if (aMap != null) {
            mapView.onDestroy();
            aMap.clear();
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 点击手机上的返回键，返回上一层
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            closeCurrentActivity();
        }
        return false;
    }

    private void closeCurrentActivity() {
        if (trackFlag) {
//            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
//                //判断悬浮窗权限是否开启
//                boolean isAlertWindow = XXPermissions.isGranted(this, Permission.SYSTEM_ALERT_WINDOW);
//                if (!isAlertWindow) {
//                    new XPopup.Builder(this)
//                            .isDestroyOnDismiss(true)
//                            .dismissOnTouchOutside(true)
//                            .hasShadowBg(true)
//                            .asConfirm("提示！", "后台巡护，需要您授权悬浮窗权限",
//                                    "取消", "确定",
//                                    new OnConfirmListener() {
//                                        @Override
//                                        public void onConfirm() {
//                                            XXPermissions.with(TrackActivity.this).
//                                                    permission(Permission.SYSTEM_ALERT_WINDOW).
//                                                    request(new OnPermissionCallback() {
//                                                        @Override
//                                                        public void onGranted(List<String> permissions, boolean all) {
//                                                            //打开悬浮窗
//                                                            showFloatWindow();
//
//                                                        }
//
//                                                        @Override
//                                                        public void onDenied(List<String> permissions, boolean never) {
//
//                                                        }
//                                                    });
//                                        }
//                                    }, null, false)
//                            .show();
//                } else {
//                    //打开悬浮窗
//                    showFloatWindow();
//                }
//            } else {
            BasePopupView popupView = new XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .dismissOnTouchOutside(true)
                    .hasShadowBg(true)
                    .asConfirm(context.getResources().getString(R.string.text_tip), "巡护进行中，请先结束巡护哦~",
                            context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),

                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    strackEndEvent();
                                }
                            }, null, false);
            popupView.show();
//            }

        } else {
            ActivityUtil.removeActivity(this);
        }
    }

    private void showFloatWindow() {
        EasyFloat.with(getApplicationContext())
                .setTag("trackEvent")
                .setShowPattern(ShowPattern.FOREGROUND)
                .setLayout(R.layout.layout_drag_post, view -> {
                            view.findViewById(R.id.iv_identify).setOnClickListener(v1 -> {


                            });
                            view.findViewById(R.id.iv_reply).setOnClickListener(v1 -> {

                            });
                        }
                )
                .setSidePattern(SidePattern.RESULT_SIDE)
                .setDragEnable(true)
                .setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, -(SizeUtils.dp2px(90)))
                .registerCallbacks(new OnFloatCallbacks() {
                    @Override
                    public void createdResult(boolean b, @org.jetbrains.annotations.Nullable String s, @org.jetbrains.annotations.Nullable View view) {

                    }

                    @Override
                    public void show(@NotNull View view) {

                    }

                    @Override
                    public void hide(@NotNull View view) {

                    }

                    @Override
                    public void dismiss() {

                    }

                    @Override
                    public void touchEvent(@NotNull View view, @NotNull MotionEvent motionEvent) {

                    }

                    @Override
                    public void drag(@NotNull View view, @NotNull MotionEvent motionEvent) {

                    }

                    @Override
                    public void dragEnd(@NotNull View view) {

                    }
                })
                .show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_CODE_ONE) {
            if (resultCode == Constant.RESULT_CODE_ONE) {
                //从巡护结束界面返回后，格式化数据
                initMapData();
            }
        }

        if (requestCode == Constant.REQUEST_CODE_TWO) {
            //从定位设置界面返回
            try {
                boolean gpsState = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (gpsState) {
                    if (location == null) {
                        ToastUtils.showLong("还未获取到定位，稍后重试");
                        return;
                    }
                    if (myAMapLocation != null && mListener != null) { //防止点击定位按钮的时候不出现小蓝点
                        mListener.onLocationChanged(myAMapLocation);// 显示系统小蓝点
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                    } else {
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, Permission.ACCESS_COARSE_LOCATION) || XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) {
                initGpsStatus();
            } else {
                ToastUtils.showLong("GPS权限获取失败");
            }
        }


    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == XXPermissions.REQUEST_CODE) {
//            if (XXPermissions.isGranted(this, Permission.ACCESS_COARSE_LOCATION) || XXPermissions.isGranted(this, Permission.ACCESS_FINE_LOCATION)) {
//                initGpsStatus();
//            } else {
//                ToastUtils.showLong("GPS权限获取失败");
//            }
//        }
//
//
//    }

    /**
     * 激活定位
     *
     * @param listener
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (locationClient == null) {
            try {
                AMapLocationClient.updatePrivacyShow(context, true, true);
                AMapLocationClient.updatePrivacyAgree(context, true);
                locationClient = new AMapLocationClient(BaseApplication.getContext());
                AMapLocationClientOption option = new AMapLocationClientOption();
                //设置定位监听
                //设置为高精度定位模式
                option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                //设获取高精度模式下单次定位是否优先返回卫星定位信息,只有在单次定位高精度定位模式下有效
                //为true时，会等待卫星定位结果返回，最多等待30秒，若30秒后仍无卫星定位结果返回，返回网络定位结果
                option.setGpsFirst(true);
                option.setGpsFirstTimeout(5 * 1000);
                //option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
                //定位场景
                option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Sport);
                //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
                option.setInterval(Constant.LOCATION_INTERVAL_TIME);
                //自3.1.0版本开始，不限定定位类型，当定位类型不是AMapLocation.LOCATION_TYPE_GPS时，可以通过 AMapLocationClientOption.setSensorEnable(boolean) 控制是否返回速度值，当设置为true时会通过手机传感器获取速度,如果手机没有对应的传感器会返回0.0
                option.setSensorEnable(true);
                //设置定位参数
                locationClient.setLocationOption(option);
                locationClient.disableBackgroundLocation(true);
//                locationClient.enableBackgroundLocation(NotificationUtils.NOTIFY_ID, NotificationUtils.buildNotification(BaseApplication.getContext()));
                // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
                // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
                // 在定位结束后，在合适的生命周期调用onDestroy()方法
                // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
                locationClient.startLocation();
                locationClient.setLocationListener(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (locationClient != null) {
            locationClient.stopLocation();
        }
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {

                locationNum++;
                double longitude = aMapLocation.getLongitude();
                double latitude = aMapLocation.getLatitude();
                locationTime = aMapLocation.getTime();
                float speed = aMapLocation.getSpeed();
                float bearing = aMapLocation.getBearing();
                float accuracy = aMapLocation.getAccuracy();
                location = new LatLng(latitude, longitude);
                myAMapLocation = aMapLocation; //定位的时候用

                if (timeUtils != null) {
                    if (trackFlag && timeUtils.getTime() >= MyConstant.TRACK_AUTO_END_TIME) { //打开巡护，并且巡护时间超过12个小时自动结束巡护
                        //结束巡护
                        strackEndEvent();
                        SPStaticUtils.put(SPTools.GeoFenceFlag, Constant.AUTO_END_TRACK_TYPE_ONE);
                    }
                }

                //实时的上报位置,上报功能打开并且 是联网的情况下才执行上报方法,间隔30S会认为已经停止运行，为了节约电量，16s上报一次
                if (locationNum % 8 == 0 && Constant.getInstance().IS_OPEN_REAL_TIME_UPLOAD && netWorkState) {
                    uploadLocation(latitude + "", longitude + "", MyUtills.stampToDateTime2(String.valueOf(System.currentTimeMillis())));
                }
                if (locationNum == 1) {
                    //第一次定位将地图移动到蓝点
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                    mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
//                openAllLayer();
                }

                String address = aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                String province = aMapLocation.getProvince();//省信息
                String city = aMapLocation.getCity();//城市信息
                String district = aMapLocation.getDistrict();//城区信息
                String street = aMapLocation.getStreet();//街道信息
                String aoiName = aMapLocation.getAoiName();//定位点信息
                String description = aMapLocation.getDescription();
//            MyLogUtil.e(TAG, "lat+++" + latitude + "++longitude++" + longitude);
//            MyLogUtil.e(TAG, "Description+++" + aMapLocation.getDescription()); //在郑州莲花堂中医院附近
//            MyLogUtil.e(TAG, "AdCode+++" + aMapLocation.getAdCode());//410104
//            MyLogUtil.e(TAG, "AoiName+++" + aMapLocation.getAoiName());//源升金锣湾
//            MyLogUtil.e(TAG, "PoiName+++" + aMapLocation.getPoiName());//郑州莲花堂中医院
//            MyLogUtil.e(TAG, "Street+++" + aMapLocation.getStreet());//刘庄街
//            MyLogUtil.e(TAG, "Address+++" + aMapLocation.getAddress());//河南省郑州市管城回族区刘庄街418号靠近郑州莲花堂中医院

//                MyLogUtil.e(TAG, "locationTime=====" + MyUtills.stampToDateTime2(locationTime + "") + ",tvTime==" + tvTime.getText().toString());

                String detailsAddress = province + city + district + street + aoiName;

                if (StringUtils.isEmpty(aoiName)) {
                    detailsAddress = address;
                    aoiName = description;
                }

                SPStaticUtils.put(SPTools.aoiName, aoiName);
                SPStaticUtils.put(SPTools.address, detailsAddress);
                SPStaticUtils.put(SPTools.lat, latitude + "");
                SPStaticUtils.put(SPTools.lng, longitude + "");
                SPStaticUtils.put(SPTools.city, city);
                locationCity = city;

                if (!StringUtils.isEmpty(locationCity)) {
                    locationCityNum += 1;
                }

                if (!StringUtils.isEmpty(locationCity) && locationCityNum == 1) {
                    initOfflineMap();
                }

                //有时候会返回(0，0)点需要排除
                if (latitude == 0f || longitude <= 0.001f) {
                    return;
                }


                if (locationHashMap != null) {
                    //不等于空的时候将存的点取出来，与当前点进行对比，如果距离小于3米就不进行存储
                    List<LatLng> doublePointLatLngs = new ArrayList<>();
                    LatLng storageLocation = (LatLng) locationHashMap.get("location");
                    long storageLocationTime = (long) locationHashMap.get("locationTime");
                    doublePointLatLngs.add(storageLocation);
                    doublePointLatLngs.add(location);
                    //计算距离
                    float distance = getDistance(doublePointLatLngs);

                    //计算速度
                    long timeDev = (locationTime - storageLocationTime) / 1000; //两个点的时间差值,单位秒
                    float mySpeed = distance / (int) timeDev;

                    String ss = "maxSensorValue==" + maxSensorValue + "||,timeDev==" + timeDev +
                            "||,mySpeed==" + mySpeed +
                            "||,speed==" + speed +
                            "||,isSports==" + isSports +
                            "||,speedDev==" + Math.abs(mySpeed - speed) +
                            "||,distance==" + distance;

                    //测试代码
//                    if (trackFlag == true) {
//                        HashMap<String, String> hashMap = new HashMap<>();
//                        String key = MyUtills.stampToDateTime(System.currentTimeMillis() + "");
//                        hashMap.put(key, ss);
//                        myTestList.add(hashMap);
//                        myTestHashMap.put("testData", myTestList);
//                        String testStr = GsonUtils.toJson(myTestHashMap);
//                        String logPath = PathUtils.getCachePathExternalFirst() + "/testtest/" + timeStampStart + ".txt";
//                        FileIOUtils.writeFileFromBytesByChannel(logPath, testStr.getBytes(), true);
//                    }


                    locationHashMap.put("location", location);
                    locationHashMap.put("locationTime", locationTime);

                    // 正常行走、跑步、骑行速度不会超过5m/s,
                    // 先判断物体是否移动，timeDev == 0或者speed == 0说明物体没有移动，不为0说明物体在移动，
                    // 移动的时候分为匀速移动和非匀速移动，此过程中都有可能发生漂移的情况，物体发生移动，判断物体速度，根据mySpeed 和 speed 差值 判断是否发生漂移

                    if (timeDev == 0) { //时间间隔为0或者speed为0，说明物体未移动
                        return;
                    }

                    if (Float.isNaN(mySpeed)) {
                        return;
                    }


                    if (mySpeed > 40) { //移动太快，是漂移情况
                        return;
                    }
                    //此处isSports==false为匀速运动或者静止，isSports==true为非匀速运动(步行或者骑行),所以此值不做判断依据
                    //物体在非匀速移动,速度差值mySpeed和 speed 速度相近，根据差值绝对值判断否则为漂移
                    float speedDev = Math.abs(mySpeed - speed);
                    if (speedDev > 1.5) {
                        return;
                    }

                    if (!isSports) {
                        if (mySpeed < 1.25) {
                            return;
                        }
                    }


                    LatLng kalmanFilterPoint = mpathSmoothTool.kalmanFilterPoint(storageLocation, location); //单点滤波
                    location = kalmanFilterPoint;
                    aMapLocation.setLatitude(kalmanFilterPoint.latitude);
                    aMapLocation.setLongitude(kalmanFilterPoint.longitude);

//                    locationHashMap.put("location", location); //此处代码和上面的上面的不重复,保存滤波后的数据，但是此处代码会造成计算速度和实际的速度不符
//                    locationHashMap.put("locationTime", locationTime);

                    mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                    addLocpath(location, locationTime, aMapLocation);

                } else {

                    locationHashMap = new HashMap<>();
                    locationHashMap.put("location", location);
                    locationHashMap.put("locationTime", locationTime);
                    mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                    addLocpath(location, locationTime, aMapLocation);

                }

            } else {
                //定位失败
                StringBuffer sb1 = new StringBuffer();
                sb1.append("定位失败" + "\n");
                sb1.append("错误码:" + aMapLocation.getErrorCode() + "\n");
                sb1.append("错误信息:" + aMapLocation.getErrorInfo() + "\n");
                sb1.append("错误描述:" + aMapLocation.getLocationDetail() + "\n");
                MyLogUtil.e("loaction", sb1.toString());

                StringBuffer sb2 = new StringBuffer();
                sb1.append("定位失败" + "\n");
                sb2.append("* WIFI开关：").append(aMapLocation.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
                sb2.append("* GPS状态：").append(getGPSStatusString(aMapLocation.getLocationQualityReport().getGPSStatus())).append("\n");
//            if (!netStatus) {
//                ToastUtils.showLong("网络未连接，" + getGPSStatusString(aMapLocation.getLocationQualityReport().getGPSStatus()));
//            }


                MyLogUtil.e("loaction", sb2.toString());
                if (locationNum == 1 && SPStaticUtils.contains(SPTools.token)) {
                    ToastUtils.showLong(sb2.toString());
                }
            }
        }

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        return false;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(context).inflate(R.layout.bubble_view2, null);
        }
        render(marker, infoWindow);
        return infoWindow;

    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        String title = marker.getTitle();
        TextView titleUi = ((TextView) view.findViewById(R.id.title));
        titleUi.setText(title);
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        marker.hideInfoWindow();
    }

    @Override
    public void onAllTaskEnd() {
        String test = FileUtils.getSize(File_Directory);
        MyLogUtil.e("filesize", "filesize==" + test);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnClick({R.id.iv_location, R.id.iv_upload_location, R.id.iv_back,
            R.id.iv_collect, R.id.iv_start, R.id.iv_switch,
            R.id.tv_set_interest, R.id.tv_sure_pop, R.id.tv_cancle_pop,
            R.id.tv_reset_track, R.id.tv_continue_track, R.id.iv_close_pop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                closeCurrentActivity();
                break;
            case R.id.iv_switch:
                if (isSwitch) {
                    isSwitch = false;
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                    tileOverlay.setVisible(false);
                    immersionBar.statusBarDarkFont(true);
                    immersionBar.init();
                } else {
                    isSwitch = true;
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                    tileOverlay.setVisible(true);
                    immersionBar.statusBarDarkFont(false);
                    immersionBar.init();
                }
                break;
            case R.id.tv_set_interest://设置兴趣点
                layoutPopEdit.setVisibility(View.VISIBLE);
                tvSetInterest.setVisibility(View.GONE);
                break;
            case R.id.tv_cancle_pop: //取消兴趣点设置
                layoutPopEdit.setVisibility(View.GONE);
                tvSetInterest.setVisibility(View.VISIBLE);
                break;

            case R.id.tv_sure_pop://确定兴趣点设置
                tvSetInterest.setVisibility(View.VISIBLE);
                interestName = MyUtills.getEditText(editInterest);
                if (!StringUtils.isEmpty(interestName)) {
                    setInterest();
                } else {
                    ToastUtils.showLong("请输入兴趣点名字！");
                }

                break;
            case R.id.iv_location://定位位置

                //测试代码
//                List<File> fileList = FileUtils.listFilesInDir(PathUtils.getCachePathExternalFirst() + "/testtest2");
//                if (fileList != null) {
//                    int size = fileList.size();
//                    if (size > 0) {
//                        for (int i = 0; i < size; i++) {
//                            File file = fileList.get(i);
//                            byte[] bytes = FileIOUtils.readFile2BytesByChannel(file);
//                            String string = new String(bytes);
//                            String string1 = new String(bytes);
//                        }
//                    }
//                }

                if (locationManager != null) {


                    boolean gpsState = false;
                    try {
                        MyLogUtil.e(TAG, "gpsState==1==" + locationManager);
                        gpsState = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                        MyLogUtil.e(TAG, "gpsState==2==" + gpsState);
                    } catch (Exception e) {
                        ToastUtils.showLong("未获取到GPS定位权限");
                        e.printStackTrace();
                    }

                    if (!netWorkState && !gpsState) {
                        ToastUtils.showLong("请打开GPS和数据网络");
                        return;
                    } else {
//                    if (!netWorkState) {
//                        ToastUtils.showLong(getResources().getString(R.string.text_no_net));
//                        return;
//                    }

                        if (!gpsState) {
                            ToastUtils.showLong("请打开GPS设置");
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, Constant.REQUEST_CODE_TWO);
                            return;
                        }
                    }

                    if (location == null) {
                        ToastUtils.showLong("还未获取到定位，稍后重试");
                        return;
                    }
                    if (myAMapLocation != null && mListener != null) { //防止点击定位按钮的时候不出现小蓝点
                        mListener.onLocationChanged(myAMapLocation);// 显示系统小蓝点
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                    } else {
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
                    }
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));
                    //进来的时候处于离线状态，并且未获取到当前城市定位，需要手动定位定位下当前城市
                    if (!StringUtils.isEmpty(locationCity)) {
                        initOfflineMap();
                    }
                } else {
                    new XPopup.Builder(this)
                            .isDestroyOnDismiss(true)
                            .dismissOnTouchOutside(true)
                            .hasShadowBg(true)
                            .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_location_auth),
                                    context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),

                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            List<String> permissions = new ArrayList<>();
                                            permissions.add(Permission.ACCESS_COARSE_LOCATION);
                                            permissions.add(Permission.ACCESS_FINE_LOCATION);
                                            XXPermissions.startPermissionActivity(TrackActivity.this, permissions);
                                        }
                                    }, null, false)
                            .show();
                }
                break;

            case R.id.iv_upload_location: //上传坐标
                if (location != null) {

                    double lng = location.longitude;
                    double lat = location.latitude;
                    LatLng latLng = new LatLng(lat, lng);
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put(locationTime + "", latLng);
                    uploadLocationList.add(hashMap);

                    MarkerOptions markerOptions = new MarkerOptions()
                            .position(latLng)
                            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_upload_marker));
                    Marker Marker = aMap.addMarker(markerOptions);
                    locationMarkers.add(Marker);

                } else {
                    ToastUtils.showLong("还未获取到定位信息哦~");
                }
                break;
            case R.id.iv_start: // 开始巡护
                if (!isIgnoringBatteryOptimizations()) {
                    requestIgnoreBatteryOptimizations();
                }
                if (GeoFenceStatus == false && Constant.getInstance().IS_OPEN_GEOFENCE) {
                    ToastUtils.showLong(context.getResources().getString(R.string.text_geo_fence));
                    return;
                }
                strackStartEvent();
                break;
            case R.id.iv_close_pop:
                popupView = new XPopup.Builder(this)
                        .isDestroyOnDismiss(false)
                        .popupHeight(SizeUtils.dp2px(170))
                        .dismissOnTouchOutside(false)
                        .hasShadowBg(false)
                        .asConfirm(context.getResources().getString(R.string.text_tip), "还未结束的巡护数据会被清除，确认要执行此操作吗？",
                                context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),

                                new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        initMapData();
                                        layoutPopTips.setVisibility(View.GONE);
                                    }
                                }, null, false);
                popupView.show();
                break;
            case R.id.tv_reset_track:
                //重新开始巡护
                if (GeoFenceStatus == false && Constant.getInstance().IS_OPEN_GEOFENCE) {
                    ToastUtils.showLong(context.getResources().getString(R.string.text_geo_fence));
                    return;
                }
                SPStaticUtils.remove(SPTools.trackTime);
                SPStaticUtils.remove(SPTools.uploadHistoryStr);
                strackStartEvent();
                layoutPopTips.setVisibility(View.GONE);
                break;
            case R.id.tv_continue_track:
                //继续上次巡护
                if (GeoFenceStatus == false && Constant.getInstance().IS_OPEN_GEOFENCE) {
                    ToastUtils.showLong(context.getResources().getString(R.string.text_geo_fence));
                    return;
                }
                List<TrackHistoryEvent> trackHistoryEvents = trackHistoryEventDao.getAll();
                if (trackHistoryEvents.size() > 0) {
                    //时间逻辑
                    String myStamp = SPStaticUtils.getString(SPTools.trackStartTimeTamp); //继续巡护之前，需要判断一下事件是否为空，防止开始时间出现1970
                    if (StringUtils.isEmpty(myStamp) || myStamp == "0") {
                        ToastUtils.showLong("巡护数据失效，请重新开始巡护");
                        return;
                    } else {
                        Calendar currentTime = Calendar.getInstance();
                        long currentTimeMillis = currentTime.getTimeInMillis();
                        if (currentTimeMillis - Long.parseLong(myStamp) >= 12 * 60 * 60 * 1000) {
                            ToastUtils.showLong("巡护时间异常，请重新开始巡护");
                            return;
                        }
                    }

                    for (int i = 0; i < trackHistoryEvents.size(); i++) {
                        TrackHistoryEvent trackHistoryEvent = trackHistoryEvents.get(i);
                        List<TrackHistoryEvent.PointBean> pointBeans = trackHistoryEvent.getHistoryPonits();
                        List<LatLng> latLngs = new ArrayList<>();
                        for (int k = 0; k < pointBeans.size(); k++) {
                            TrackHistoryEvent.PointBean pointBean = pointBeans.get(k);
                            double lat = pointBean.getLatitude();
                            double lng = pointBean.getLongitude();
                            LatLng latLng = new LatLng(lat, lng);
                            latLngs.add(latLng);
                            if (i == 0 && k == 0) {
                                MarkerOptions startMarkerOptions = new MarkerOptions()
                                        .position(latLng)
                                        .zIndex(MAP_INDEX)
                                        .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_start));
                                Marker startMarker = aMap.addMarker(startMarkerOptions);
                                endMarkers.add(startMarker);
                            }
                        }
                        //上次的巡护轨迹平滑处理
//                            List<LatLng> lastLatLngListOp = mpathSmoothTool.pathOptimize(latLngs);
                        Polyline lastMapPolyline = aMap.addPolyline(new PolylineOptions()
                                .addAll(latLngs)
                                .width(Constant.POLYLINE_WIDTH)
                                .zIndex(MAP_INDEX)
                                .color(context.getResources().getColor(R.color.colorPrimary)));
                        historyPolylines.add(lastMapPolyline);

                        //取最后一个历史数据的distance字段
                        if (i == trackHistoryEvents.size() - 1) {
                            String myDistance = trackHistoryEvent.getDistance();//单位是千米
                            tvMileage.setText(myDistance + "");
                            toatalDistance = Float.parseFloat(myDistance) * 1000; //单位是米
                        }
                    }


                    //上报地点逻辑
                    String uploadHistory = SPStaticUtils.getString(SPTools.uploadHistoryStr);
                    if (!StringUtils.isEmpty(uploadHistory)) {
                        JSONObject uJsonObject = JSON.parseObject(uploadHistory);
                        JSONArray uJsonArray = uJsonObject.getJSONArray("uploadHistory");
                        for (int i = 0; i < uJsonArray.size(); i++) {


                            JSONObject object = uJsonArray.getJSONObject(i);
                            String longitude = object.getString("longitude");
                            String latitude = object.getString("latitude");
                            String locationTime = object.getString("locationTime");

                            LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));

                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put(locationTime, latLng);
                            uploadLocationList.add(hashMap);


                            MarkerOptions markerOptions = new MarkerOptions()
                                    .position(latLng)
                                    .zIndex(MAP_INDEX)
                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_upload_marker));
                            Marker Marker = aMap.addMarker(markerOptions);
                            locationMarkers.add(Marker);

                        }

                    }

                    strackContinueEvent();//继续巡护事件
                    layoutPopTips.setVisibility(View.GONE);
                } else {
                    ToastUtils.showLong("抱歉，未获取到上次的巡护记录");
                }

                uploadToTrack = false;
                break;
        }
    }


    /**
     * 巡护历史事件(结束巡护时，执行此方法后，需要将保存的数据置空，防止弹出继续巡护的弹框)
     */
    private void trackHistoryEvent(ResultCallback resultCallback) {
        //保存历史巡护记录
        if (tvMileage == null) {
            return; //第一次进入APP的时候，未获取到view 就走Destory 跳转到登录页面
        }
        String distance = MyUtills.getTextView(tvMileage);
        double formateDis = Double.parseDouble(distance);

        if (locationInfoMap.size() > 0 && formateDis >= 0.01) {

            List<TrackHistoryEvent.PointBean> pointBeans = new ArrayList<>();
            for (String key : locationInfoMap.keySet()) {
                AMapLocation aMapLocation = (AMapLocation) locationInfoMap.get(key); //键是时间，值是aMapLocation
                double longitude = aMapLocation.getLongitude();
                double latitude = aMapLocation.getLatitude();
                String district = aMapLocation.getDistrict();
                String street = aMapLocation.getStreet();
                TrackHistoryEvent.PointBean pointBean = new TrackHistoryEvent.PointBean();
                pointBean.setGeoFenceIn(false);//默认在巡护区域外
                for (Polygon polygon : trackPolygonList) {
                    if (polygon.contains(new LatLng(latitude, longitude))) {
                        pointBean.setGeoFenceIn(true);
                        ;
                    }
                }
                pointBean.setLocationTime(key);
                pointBean.setLongitude(longitude);
                pointBean.setLatitude(latitude);
                pointBean.setDistrict(district);
                pointBean.setStreet(street);
                pointBeans.add(pointBean);
            }

            TrackHistoryEvent trackHistoryEvent = new TrackHistoryEvent();
            trackHistoryEvent.setDistance(distance);
            trackHistoryEvent.setHistoryPonits(pointBeans);
            trackHistoryEventDao.insertEvent(trackHistoryEvent);

            locationInfoMap.clear();//防止存储的数据重复
            if (resultCallback != null) {
                resultCallback.result(true);
            }
        }


    }

    /**
     * 初始化离线地图
     */
    private void initOfflineMap() {
        MyLogUtil.e("offline", "initOfflineMap===");
        //构造离线地图类
        try {
            MapsInitializer.updatePrivacyShow(context, true, true);
            MapsInitializer.updatePrivacyAgree(context, true);
            offlineMapManager = new OfflineMapManager(getApplicationContext(), null);
            offlineMapManager.setOnOfflineLoadedListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //离线地图初始化完成监听

    }

    /**
     * 判断定位的离线地图是否存在
     */
    private void haveLocationOfflineMap(OfflineMapManager offlineMapManager, String locationCity, ResultCallback resultCallback) {
        List<String> cityList = new ArrayList<>();
        ArrayList<OfflineMapCity> offlineMapCities = offlineMapManager.getDownloadOfflineMapCityList(); //获取下载好的离线地图用于判断离线地图是否下载
        if (offlineMapCities != null) {
            if (offlineMapCities.size() > 0) {
                //存在离线地图
                for (int i = 0; i < offlineMapCities.size(); i++) {
                    String city = offlineMapCities.get(i).getCity();
                    cityList.add(city);
                }
                if (cityList.contains(locationCity)) {
                    //下载了当前城市的离线地图
                    resultCallback.result(true);
                } else {
                    resultCallback.result(false);
                }
            } else {
                resultCallback.result(false);
            }
        } else {
            resultCallback.result(false);
        }
    }


    /**
     * 初始化长按的进度动画
     */
    private void initAnimator() {
        animator = ValueAnimator.ofInt(0, 100);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int progress = (int) animation.getAnimatedValue();
                circleProgress.setProgress(progress);
                if (progress >= 99) {
                    animation.cancel(); //防止重复的执行结束方法
                    circleProgress.setProgress(0);
                    strackEndEvent();
                }
            }
        });
        animator.setRepeatCount(ValueAnimator.RESTART);
        animator.setDuration(1500);
    }

    /**
     * 初始化GPS状态相关
     */
    public void initGpsStatus() {
        XXPermissions.with(this)
                .permission(Permission.ACCESS_BACKGROUND_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        MyLogUtil.e("testest", "all===" + all);
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        MyLogUtil.e("testest", "never===" + never);
                    }
                });

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        try {
            proxy = GpsStatusProxy.getInstance(getApplicationContext());
            proxy.register();
            locationManager = (LocationManager) BaseApplication.getBaseApplication().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Constant.LOCATION_INTERVAL_TIME, 1, myLocationListener);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private LocationListener myLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            proxy.notifyLocation(location);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };


    /**
     * 动态的设置定位点图标的位置
     */
    private void setIvLocationMargin(int bottomMargin) {
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) ivLocation.getLayoutParams();
        layoutParams.bottomMargin = bottomMargin;
        ivLocation.setLayoutParams(layoutParams);
    }

    /**
     * 在地图上添加本地轨迹数据
     */
    private void addLocpath(LatLng myLocation, long locationTime, AMapLocation aMapLocation) {
        if (mOriginList != null && trackFlag == true) { //点击开始的按钮的时候在收集轨迹点

            int signalStatus = gpsImage.getSignalStrength();//信号强弱

            if (signalStatus == 0 && locationNum % 50 == 0) {
//                ToastUtils.showLong("没有GPS信号，请移动到开阔地带");
                PlayMusicUtils.playSound(this, "gpsVoice1.mp3");
            }
            if (signalStatus == 1 && locationNum % 50 == 0) {
//                ToastUtils.showLong("GPS信号较弱，请移动到开阔地带");
                PlayMusicUtils.playSound(this, "gpsVoice2.mp3");
            }

//            ***********************start**********************
//            locationInfoMap.put(myLocation, locationTime + ""); //坐标位置作为键,时间作为值，保证获取到的相同坐标的最新时间
//            for (Map.Entry<Object, String> entry : locationInfoMap.entrySet()) {
//                LatLng latLng = (LatLng) entry.getKey();
//                mOriginList.add(latLng); //添加到原始轨迹点集合
//            }
//
//            //去重，有序排列
//            myLatLngList = new ArrayList<LatLng>(new LinkedHashSet(mOriginList));
//             *******************end**************

            mOriginList.add(myLocation);
            //去重，有序排列(次过程已经没有重复数据，为了保证和之前数据一致性，这里也执行了此操作)
            myLatLngList = new ArrayList<LatLng>(new LinkedHashSet(mOriginList));
            //绘制线路
            if (myLatLngList.size() > 0) {
                //轨迹去噪
//                optimizeLatLng = mpathSmoothTool.removeNoisePoint(myLatLngList);
                //下面所有的计算都是在估计优化之后完成，防止出现后面传递的轨迹点出现漂移的现象
                //计算距离
                float distance = toatalDistance + getDistance(myLatLngList);
                BigDecimal b = new BigDecimal(String.valueOf(distance / 1000));
                double myDistance = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); //四舍五入，保留两位小数
                tvMileage.setText(myDistance + "");
                EventBus.getDefault().post(new MyEventBus(MyConstant.LOCK_SCREEN_MILEAGE_DATA, myDistance + ""));

                locationInfoMap.put(locationTime + "", aMapLocation);

                //为了保持一条轨迹线，每次画线之前需要先清空线
                if (polylines.size() > 0) {
                    for (Polyline polyline : polylines) {
                        polyline.remove();
                    }
                    polylines.clear();
                }


                mapPolyline = aMap.addPolyline(new PolylineOptions()
                        .addAll(myLatLngList)
                        .width(Constant.POLYLINE_WIDTH)
                        .zIndex(MAP_INDEX)
                        .color(context.getResources().getColor(R.color.colorPrimary)));
                polylines.add(mapPolyline);

//                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(optimizeLatLng), 200));

            }

        }

    }


    /**
     * 初始化地图
     */
    private void initMap() {
        aMap = mapView.getMap();
        aMap.setLocationSource(this);// 设置定位监听
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。

        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(
                BitmapDescriptorFactory.fromResource(R.mipmap.gps_point));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(Color.argb(100, 47, 185, 97));
        // 自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(0.1F);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 47, 185, 97));
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
//        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
//                getAreaData();
            }
        });
        mpathSmoothTool = new PathSmoothTool();
        mpathSmoothTool.setIntensity(Constant.Intensity);
        mpathSmoothTool.setThreshhold(0);

        tileOverlayOptions = TileUtils.getTileOverlayOptions();
        tileOverlay = aMap.addTileOverlay(tileOverlayOptions); //自定义瓦片图层  ，默认隐藏

    }


    public void setMapType(int type) {
        switch (type) {
            case 0:
                aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                tileOverlay.setVisible(false);
                break;
            case 1:
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                tileOverlay.setVisible(true);
                break;
            case 2: //谷歌地图切片
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                tileOverlay.setVisible(true);
                break;
        }

    }

    /**
     * 获取GPS状态的字符串
     *
     * @param statusCode GPS状态码
     * @return
     */
    private String getGPSStatusString(int statusCode) {
        String str = "";
        switch (statusCode) {
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }


    /**
     * 清空track
     */
    private void clearTracksOnMap() {
        for (Polyline polyline : polylines) {
            polyline.remove();
        }
        for (Polyline polyline : historyPolylines) {
            polyline.remove();
        }
        for (Marker marker : endMarkers) {
            marker.remove();
        }
        for (Marker marker : locationMarkers) {
            marker.remove();
        }
        endMarkers.clear();
        polylines.clear();
        historyPolylines.clear();
        locationMarkers.clear();
    }


    /**
     * 初始化地图相关数据
     */
    private void initMapData() {
        if (locationClient != null) {
            locationClient.startLocation(); //定位
        }
        mOriginList = null;
        locationHashMap = null;
        locationInfoMap.clear();
        myLatLngList.clear();
        uploadLocationList.clear();
        myUploadLocationList.clear();
        tvMileage.setText("0.0");
        tvTime.setText("00h : 00m : 00s");
        toatalDistance = 0;
        clearTracksOnMap();
        //获取到轨迹数据清空数据，防止继续巡护弹框弹出
        trackHistoryEventDao.removeAll();

        if (myAMapLocation != null && mListener != null) { //防止点击定位按钮的时候不出现小蓝点
            mListener.onLocationChanged(myAMapLocation);// 显示系统小蓝点
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        } else {
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }
    }


    /**
     * 计算距离
     */
    private float getDistance(List<LatLng> list) {
        float distance = 0;
        if (list == null || list.size() == 0) {
            return distance;
        }
        for (int i = 0; i < list.size() - 1; i++) {
            LatLng firstLatLng = list.get(i);
            LatLng secondLatLng = list.get(i + 1);
            double betweenDis = AMapUtils.calculateLineDistance(firstLatLng,
                    secondLatLng);
            distance = (float) (distance + betweenDis);
        }
        return distance;
    }

    /**
     * ****************兴趣点相关逻辑***********************
     */

    private void initInterest() {
        aMap.animateCamera(CameraUpdateFactory.newLatLng(location));
        aMap.setOnCameraChangeListener(onCameraChangeListener);

        // 添加当前坐标覆盖物
        if (markerOptionsIntetest == null) {
            markerOptionsIntetest = new MarkerOptions()
                    .icon(iconInterest)
                    .position(location)
                    .draggable(true);//设置Marker可拖动
            markerInterest = aMap.addMarker(markerOptionsIntetest);

            screenMarkerJump(markerInterest);

        } else {

        }

    }

    /**
     * 设置兴趣点
     */
    private void setInterest() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("lat", latInterest);
        hashMap.put("lng", lngInterest);
        hashMap.put("name", interestName);
        hashMap.put("type", Constant.INTEREST_TYPE_ONE);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_FAVORITE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("兴趣点设置成功！");
                                layoutPopEdit.setVisibility(View.GONE);
                                editInterest.setText("");
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }


    /**
     * 移动兴趣点监听
     */
    private AMap.OnCameraChangeListener onCameraChangeListener = new AMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {


            markerInterest.setPosition(cameraPosition.target);

        }

        @Override
        public void onCameraChangeFinish(CameraPosition cameraPosition) {
            LatLng latLng = cameraPosition.target;
            latInterest = latLng.latitude;
            lngInterest = latLng.longitude;
            MyLogUtil.e("interest location", "latitude==" + latInterest + ",longitude==" + lngInterest);
            screenMarkerJump(markerInterest);
        }
    };


    /**
     * 巡护继续事件
     */
    private void strackContinueEvent() {
        boolean gpsState = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (!netWorkState && !gpsState) {
            ToastUtils.showLong("请打开GPS和数据网络");
            return;
        } else {
            if (!netWorkState) {
                ToastUtils.showLong(getResources().getString(R.string.text_no_net));
            }

            if (!gpsState) {
                ToastUtils.showLong("请打开GPS设置");
            }
        }


        ivStart.setVisibility(View.GONE);
        layoutBottomMileage.setVisibility(View.VISIBLE);
//        ivUploadLocation.setVisibility(View.VISIBLE);
        //定位图标离底部的距离
        setIvLocationMargin(SizeUtils.dp2px(130));


        trackFlag = true;
        SPStaticUtils.put(SPTools.trackFlag, "true");//记录巡护的状态

        //重新开始巡护的的时间逻辑
        String trackTime = SPStaticUtils.getString(SPTools.trackTime);
        if (!StringUtils.isEmpty(trackTime)) {
            timeUtils = new TimeUtils(tvTime);
            timeUtils.setTime(Long.parseLong(trackTime));
            timeUtils.startTimer();

            String myStamp = SPStaticUtils.getString(SPTools.trackStartTimeTamp);
            timeStampStart = Long.parseLong(myStamp);
        }

        //只有巡护的时候，才将视角移动到地图中心
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        aMap.setMyLocationStyle(myLocationStyle);

        //监听锁屏
        addScreenChangeBroadCast();

        //传感器
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
        sensorManager.registerListener(new MySensorEventListener(), sensor, SensorManager.SENSOR_DELAY_NORMAL);

    }


    /**
     * 巡护开始事件
     */
    private void strackStartEvent() {
        try {
            boolean gpsState = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            if (!netWorkState && !gpsState) {
                ToastUtils.showLong("请打开GPS和数据网络");
                return;
            } else {
                if (!netWorkState) {
                    ToastUtils.showLong(getResources().getString(R.string.text_no_net));
                }

                if (!gpsState) {
                    ToastUtils.showLong("请打开GPS设置");
                }
            }
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }

        PlayMusicUtils.playSound(ActivityUtil.getTopActivity(), "startTrack.mp3");

        ivStart.setVisibility(View.GONE);
        layoutBottomMileage.setVisibility(View.VISIBLE);
//        ivUploadLocation.setVisibility(View.VISIBLE);
        uploadLocationList.clear();
        myUploadLocationList.clear();
        //定位图标离底部的距离
        setIvLocationMargin(SizeUtils.dp2px(130));

        //原始轨迹点
        mOriginList = new ArrayList<LatLng>();
        trackFlag = true;
        SPStaticUtils.put(SPTools.trackFlag, "true"); //记录巡护的状态
        //计时
        timeUtils = new TimeUtils(tvTime);

        //重新开始巡护的的时间逻辑
        timeUtils.setTime(0);
        timeUtils.startTimer();

        timeStampStart = System.currentTimeMillis();
        SPStaticUtils.put(SPTools.trackStartTimeTamp, timeStampStart + "");
        //清空轨迹数据，防止结束巡护之后，关闭进程 再次开始巡护的时候，计算上次巡护的历史数据
        trackHistoryEventDao.removeAll();
        //清空坐标数据,防止里程计算错误
        locationInfoMap.clear();
        tvMileage.setText("0.0");
        SPStaticUtils.put(SPTools.GeoFenceFlag, ""); //自动结束之后，放回重新开始后的时候将数据值null
//        mOriginList.clear();

//        testList.clear();
//        drawTrackLatLngs.clear();
        //鹰眼服务
//        startTrack();
//        //轨迹纠偏方法
//        startTrace();

        //添加开始Marker
        LatLng startPositon = null;
        if (locationHashMap == null) {
            startPositon = location;
        } else {
            startPositon = (LatLng) locationHashMap.get("location");
        }

        MarkerOptions startMarkerOptions = new MarkerOptions()
                .position(startPositon)
                .zIndex(MAP_INDEX)
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_start));
        startMarker = aMap.addMarker(startMarkerOptions);
        endMarkers.add(startMarker);


        //只有巡护的时候，才将视角移动到地图中心
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        aMap.setMyLocationStyle(myLocationStyle);
        //监听锁屏
        addScreenChangeBroadCast();

        //传感器
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
        sensorManager.registerListener(new MySensorEventListener(), sensor, SensorManager.SENSOR_DELAY_NORMAL);

        //测试代码
        myTestList = new ArrayList<>();
        myTestHashMap = new HashMap<>();

    }


    /**
     * 结束巡护事件
     */
    private void strackEndEvent() {
        ivStart.setVisibility(View.VISIBLE);
        layoutBottomMileage.setVisibility(View.GONE);
//        ivUploadLocation.setVisibility(View.GONE);
        setIvLocationMargin(SizeUtils.dp2px(24));
        trackFlag = false;
        locationNum = 0;
        //记录巡护的状态
        SPStaticUtils.put(SPTools.trackFlag, "false");

        //清楚巡护的时间
        SPStaticUtils.remove(SPTools.trackTime);
        //记录巡护结束的时间戳
        timeStampEnd = System.currentTimeMillis();
        if (timeUtils != null) {
            timeUtils.stopTimer();
        }

//        long duration = (timeStampEnd - timeStampStart) / 1000 + 1; //时间戳相减，显示的结果少1秒，待研究
        long duration = timeUtils.getTime();
        String distance = MyUtills.getTextView(tvMileage);
        double formateDis = Double.parseDouble(distance);


        if (formateDis >= 0.01) {
            trackHistoryEvent(new ResultCallback() {
                @Override
                public void result(Object object) {
                    boolean b = Boolean.parseBoolean(object.toString());
                    if (b) {
                        Intent intent = new Intent(ActivityUtil.getTopActivity(), TrackEndActivity.class);
                        intent.putExtra("distance", distance);
                        intent.putExtra("duration", duration);
                        intent.putExtra("startTime", timeStampStart + "");
                        intent.putExtra("endTime", timeStampEnd + "");
                        intent.putExtra("uploadLocation", (Serializable) uploadLocationList);
                        startActivityForResult(intent, Constant.REQUEST_CODE_ONE);
                    }
                }
            });

        } else {
            ToastUtils.showLong("巡护距离太短,请重新开始");
            clearTracksOnMap();
            toatalDistance = 0;
            mOriginList = null;
            locationInfoMap.clear();
            myLatLngList.clear();
            locationHashMap = null;
        }


        uploadToTrack = true; //结束巡护后,设置true 创建新的轨迹


        //结束巡护的时候，视角不移动到地图中心
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        aMap.setMyLocationStyle(myLocationStyle);

        removeScreenChangeBroadCast();

        if (sensorManager != null) {
            sensorManager.unregisterListener(new MySensorEventListener());
        }

//        stopService();

    }


    /**
     * 兴趣点Marker动画
     */
    public void screenMarkerJump(Marker screenMarker) {
        if (screenMarker != null) {
            final LatLng latLng = screenMarker.getPosition();
            Point point = aMap.getProjection().toScreenLocation(latLng);
            point.y -= SizeUtils.dp2px(30);
            LatLng target = aMap.getProjection()
                    .fromScreenLocation(point);
            //使用TranslateAnimation,填写一个需要移动的目标点
            Animation animation = new TranslateAnimation(target);
            animation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    // 模拟重加速度的interpolator
                    if (input <= 0.5) {
                        return (float) (0.5f - 2 * (0.5 - input) * (0.5 - input));
                    } else {
                        return (float) (0.5f - Math.sqrt((input - 0.5f) * (1.5f - input)));
                    }
                }
            });
            //整个移动所需要的时间
            animation.setDuration(600);
            //设置动画
            screenMarker.setAnimation(animation);
            //开始动画
            screenMarker.startAnimation();
        }
    }

    /**
     * ****************menu相关逻辑***********************
     */
    /**
     * 业务图层事件
     *
     * @param type
     */
    public void menuEnevt(int type, boolean isChecked) {
//        ((MainActivity) getActivity()).closeDrawers();
        switch (type) {
            case 0: //功能区划
                if (isChecked) {
//                    getAreaData();

                    for (Polygon polygon : trackPolygonList) {
                        polygon.setVisible(true);
                    }

                    if (areaAllLatLng.size() > 0) {
                        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(areaAllLatLng), 200));
                    }

                } else {
//                    for (Polygon polygon : trackPolygonList) {
//                        polygon.remove();
//                    }
//                    trackPolygonList.clear();


                    for (Polygon polygon : trackPolygonList) {
                        polygon.setVisible(false);
                    }
                }

                break;

//            case 1://保护设施
//                if (isChecked) {
//                    getProtectData();
//                } else { //取消选中 的时候清除地图相关显示
//                    for (Marker marker : protectMarkers) {
//                        marker.remove();
//                    }
//                    protectMarkers.clear();
//                }
//                break;
//            case 2://古树名木
//                if (isChecked) {
//                    getTreeData();
//                } else { //取消选中 的时候清除地图相关显示
//                    for (Marker marker : treeMarkers) {
//                        marker.remove();
//                    }
//                    treeMarkers.clear();
//                }
//                break;
            case 1://智能设备
                if (isChecked) {
//                    getDeviceData();
                    startGetDeviceData();
                } else {
//                    for (Marker marker : deviceMarker) {
//                        marker.remove();
//                    }
                    stopGetDeviceData();
                }
                break;
//            case 4://苗圃场
//                if (isChecked) {
//                    getNurseryData();
//                } else {
//                    for (Polygon polygon : nuseryPolygonList) {
//                        polygon.remove();
//                    }
//                    nuseryPolygonList.clear();
//                }
//
//                break;

        }

    }

    /**
     * 打开所有业务图层
     */
    private void openAllLayer() {

//        getProtectData();
//        getTreeData();
        startGetDeviceData();
//        getNurseryData();
//        getAreaData();

        //测试围栏
//        GeoFenceData();
    }


    /**
     * 古树名木
     */
    private void getTreeData() {
        List<LatLng> latLngs = new ArrayList<>();
        OkGo.<String>get(Constant.getInstance().GET_TREE)
                .tag(this)
                .params("toIndex", "-1")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                MenuTreeBean menuTreeBean = new MenuTreeBean();
                                menuTreeBean = gson.fromJson(result, MenuTreeBean.class);

                                List<MenuTreeBean.FeaturesBean> featuresBeans = menuTreeBean.getFeatures();
                                for (int i = 0; i < featuresBeans.size(); i++) {
                                    MenuTreeBean.FeaturesBean.PropertiesBean propertiesBean = featuresBeans.get(i).getProperties();
                                    String gpslat = propertiesBean.getSMY();
                                    String gpslng = propertiesBean.getSMX();
                                    String pointName = propertiesBean.getNAME();

                                    double myLat = Double.parseDouble(gpslat);
                                    double myLng = Double.parseDouble(gpslng);

                                    double[] latlngs = GPSTransToAMap.transform(myLat, myLng);
                                    LatLng latLng = new LatLng(latlngs[0], latlngs[1]);

                                    latLngs.add(latLng);

                                    MarkerOptions markerOptions = new MarkerOptions()
                                            .position(latLng)
                                            .title(pointName)
                                            .zIndex(MAP_INDEX)
                                            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_patrol_mark_gsmm));
                                    Marker Marker = aMap.addMarker(markerOptions);
                                    treeMarkers.add(Marker);
                                }

                                if (latLngs.size() > 0) {
                                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLngs.get(0)));
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    /**
     * 苗圃场
     */
    private void getNurseryData() {
        nuseryPolygonList = new ArrayList<>();

        OkGo.<String>get(Constant.getInstance().GET_NURSERY)
                .tag(this)
                .params("toIndex", "-1")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            MenuNurseryBean menuNurseryBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                menuNurseryBean = new MenuNurseryBean();
                                menuNurseryBean = gson.fromJson(result, MenuNurseryBean.class);


                                List<MenuNurseryBean.FeaturesBean> featuresBeans = menuNurseryBean.getFeatures();
                                List<List<LatLng>> nuseryLatLngList = new ArrayList<>(); //存放所有区域的数据

                                for (int i = 0; i < featuresBeans.size(); i++) {
                                    MenuNurseryBean.FeaturesBean featuresBean = featuresBeans.get(i);
                                    List<List<List<Double>>> dataList = featuresBean.getGeometry().getCoordinates();
                                    List<List<Double>> pointList = dataList.get(0);
                                    List<LatLng> latLngs = new ArrayList<>();//存放单条区域的数据
                                    for (int j = 0; j < pointList.size(); j++) {
                                        List<Double> latLngList = pointList.get(j);
                                        double gpsLat = latLngList.get(1);
                                        double gpsLng = latLngList.get(0);
                                        //gps 转高德的经纬度
                                        double[] latlngs = GPSTransToAMap.transform(gpsLat, gpsLng);
                                        LatLng latLng = new LatLng(latlngs[0], latlngs[1]);
                                        latLngs.add(latLng); //将坐标装到数组里
                                    }

                                    Polygon mapPolygon = aMap.addPolygon(new PolygonOptions()
                                            .addAll(latLngs)
                                            .fillColor(context.getResources().getColor(R.color.bg_color5))
                                            .strokeColor(context.getResources().getColor(R.color.blue_16b))
                                            .strokeWidth(1));
                                    nuseryPolygonList.add(mapPolygon);
                                    nuseryLatLngList.add(latLngs);
                                }

                                if (nuseryLatLngList.size() > 0) {
                                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(nuseryLatLngList.get(0)), 200));
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }


    /**
     * 保护设施
     */
    private void getProtectData() {
        List<LatLng> latLngs = new ArrayList<>();
        OkGo.<String>get(Constant.getInstance().GET_PROTECT)
                .tag(this)
                .params("toIndex", "-1")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            MenuProtectBean menuProtectBean = new MenuProtectBean();
                            menuProtectBean = gson.fromJson(result, MenuProtectBean.class);

                            List<MenuProtectBean.FeaturesBean> featuresBeans = menuProtectBean.getFeatures();
                            for (int i = 0; i < featuresBeans.size(); i++) {
                                MenuProtectBean.FeaturesBean.PropertiesBean propertiesBean = featuresBeans.get(i).getProperties();
                                String gpslat = propertiesBean.getSMY();
                                String gpslng = propertiesBean.getSMX();
                                String pointName = propertiesBean.getNAME();

                                double myLat = Double.parseDouble(gpslat);
                                double myLng = Double.parseDouble(gpslng);

                                double[] latlngs = GPSTransToAMap.transform(myLat, myLng);
                                LatLng latLng = new LatLng(latlngs[0], latlngs[1]);

                                latLngs.add(latLng);

                                MarkerOptions markerOptions = new MarkerOptions()
                                        .position(latLng)
                                        .title(pointName)
                                        .zIndex(MAP_INDEX)
                                        .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_patrol_mark_bhss));
                                Marker Marker = aMap.addMarker(markerOptions);
                                protectMarkers.add(Marker);
                            }

                            if (latLngs.size() > 0) {
                                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLngs.get(0)));
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }


    /**
     * 巡护区域
     */
    private void getAreaData() {
        trackPolygonList = new ArrayList<>();
        OkGo.<String>get(MyConstant.GET_AREA)
                .tag(this)
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            ResAreaBean resAreaBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                resAreaBean = new ResAreaBean();
                                resAreaBean = gson.fromJson(result, ResAreaBean.class);

                                List<ResAreaBean.FeaturesBean> featuresBeans = resAreaBean.getFeatures();
                                List<List<LatLng>> areaLatLngList = new ArrayList<>(); //存放所有区域的数据
                                areaAllLatLng = new ArrayList<>();
                                for (int i = 0; i < featuresBeans.size(); i++) {
                                    ResAreaBean.FeaturesBean featuresBean = featuresBeans.get(i);
                                    ResAreaBean.FeaturesBean.PropertiesBeanX propertiesBeanX = featuresBean.getProperties();
                                    ResAreaBean.FeaturesBean.GeometryBean geometryBean = featuresBean.getGeometry();
                                    List<List<List<List<Double>>>> coordinates = geometryBean.getCoordinates();
                                    List<List<Double>> myList = coordinates.get(0).get(0);
                                    List<DPoint> points = new ArrayList<DPoint>();  //存放地里围栏需要的数据
                                    List<LatLng> latLngs = new ArrayList<>();//存放单条区域的数据
                                    for (int j = 0; j < myList.size(); j++) {
                                        List<Double> latLngList = myList.get(j);
                                        double gpsLat = latLngList.get(1);
                                        double gpsLng = latLngList.get(0);
                                        //gps 转高德的经纬度
//                                        double[] latlngs = GPSTransToAMap.transform(gpsLat, gpsLng);
//                                        LatLng latLng = new LatLng(latlngs[0], latlngs[1]);
//                                        points.add(new DPoint(latlngs[0], latlngs[1]));

                                        LatLng latLng = new LatLng(gpsLat, gpsLng);
                                        latLngs.add(latLng); //将坐标装到数组里
                                        points.add(new DPoint(gpsLat, gpsLng));
                                        areaAllLatLng.add(latLng);

                                    }

                                    PolygonOptions polygonOptions = new PolygonOptions();
                                    polygonOptions.addAll(latLngs);
                                    polygonOptions.strokeWidth(2);
                                    polygonOptions.zIndex(45);
                                    polygonOptions.visible(false);
                                    String gnfy = propertiesBeanX.getGnfq();
                                    switch (gnfy) {
                                        case "实验区":
                                            polygonOptions.fillColor(context.getResources().getColor(R.color.bg_color_00f2));
                                            polygonOptions.strokeColor(context.getResources().getColor(R.color.bg_color_00f));
                                            break;
                                        case "缓冲区":
                                            polygonOptions.fillColor(context.getResources().getColor(R.color.bg_color_fff2));
                                            polygonOptions.strokeColor(context.getResources().getColor(R.color.bg_color_fff));
                                            break;
                                        case "核心区":
                                            polygonOptions.fillColor(context.getResources().getColor(R.color.bg_color_ff02));
                                            polygonOptions.strokeColor(context.getResources().getColor(R.color.bg_color_ff0));
                                            break;
                                    }


                                    Polygon mapPolygon = aMap.addPolygon(polygonOptions);
                                    trackPolygonList.add(mapPolygon);
                                    areaLatLngList.add(latLngs);
//                                    if (areaAllLatLng.size() > 0) {
//                                        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(areaAllLatLng), 200));
//                                    }
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    /**
     * 智能设备
     */
    private final int UPDATE_DEVICE_DATA = 100;
    private static int delay = 0;
    private static int period = 10 * 1000;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_DEVICE_DATA:
                    getDeviceData();
                    break;
                default:
                    break;
            }
        }
    };

    public void startGetDeviceData() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    sendMessage(UPDATE_DEVICE_DATA);
                }
            };
        }
        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, delay, period);
        }

    }

    public void stopGetDeviceData() {

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }

        if (deviceMarker != null) {
            if (deviceMarker.size() > 0) {
                for (Marker marker : deviceMarker) {
                    marker.remove();
                }
            }
            deviceMarker.clear();
        }

    }

    public void sendMessage(int id) {
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    private void getDeviceData() {
        //每次创建之前需要把设备图标给清除下
        if (deviceMarker != null) {
//            MyLogUtil.e("test", "deviceMarker==" + deviceMarker.size());
            if (deviceMarker.size() > 0) {
                for (Marker marker : deviceMarker) {
                    marker.remove();
                }
                deviceMarker.clear();
            }
        }

        OkGo.<String>post(Constant.getInstance().POST_DEVICE_LIST)
                .tag(this)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                MenuDeviceBean menuDeviceBean = new MenuDeviceBean();
                                menuDeviceBean = gson.fromJson(result, MenuDeviceBean.class);

                                List<MenuDeviceBean.DataBean.OfflineListBean> offlineListBeans = menuDeviceBean.getData().getOfflineList();
                                List<MenuDeviceBean.DataBean.OnlineListBean> onlineListBeans = menuDeviceBean.getData().getOnlineList();
                                List<LatLng> latLngs = new ArrayList<>();
                                List<String> nameList = new ArrayList<>();
                                deviceMarker = new CopyOnWriteArrayList<>();
                                //暂时隐藏离线的设备
//                                for (int i = 0; i < offlineListBeans.size(); i++) {
//                                    MenuDeviceBean.DataBean.OfflineListBean offlineListBean = offlineListBeans.get(i);
//                                    try {
//                                        String lat = offlineListBean.getLat();
//                                        String lng = offlineListBean.getLng();
//                                        String name = offlineListBean.getName();
//
//                                        if (!StringUtils.isEmpty(lat) && !StringUtils.isEmpty(lng)) {
//                                            LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
//                                            latLngs.add(latLng);
//                                            nameList.add(name);
//                                        }
//
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//
//                                }

                                for (int i = 0; i < onlineListBeans.size(); i++) {
                                    MenuDeviceBean.DataBean.OnlineListBean onlineListBean = onlineListBeans.get(i);
                                    try {
                                        String lat = onlineListBean.getLat();
                                        String lng = onlineListBean.getLng();
                                        String name = onlineListBean.getName();
                                        String deviceUserId = onlineListBean.getUserId() + "";

                                        String userId = SPStaticUtils.getString(SPTools.userId); //此逻辑是为了兼容线上版本，1.0版本没有添加登录获取userId 逻辑

                                        if (StringUtils.isEmpty(userId)) { //如果userId 是null,通过接口获取到userId 后再执行对比逻辑
                                            getUserInfo(new ResultCallback() {
                                                @Override
                                                public void result(Object object) {
                                                    if (Boolean.parseBoolean(object.toString())) {
                                                        String userId = SPStaticUtils.getString(SPTools.userId);
                                                        if (!StringUtils.isEmpty(lat) && !StringUtils.isEmpty(lng) && !deviceUserId.equals(userId)) {
                                                            LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
                                                            latLngs.add(latLng);
                                                            nameList.add(name + "");
                                                        }
                                                    }
                                                }
                                            });
                                        }

                                        if (!StringUtils.isEmpty(lat) && !StringUtils.isEmpty(lng) && !deviceUserId.equals(userId)) {
                                            LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
                                            latLngs.add(latLng);
                                            nameList.add(name);
                                        }

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                for (int i = 0; i < latLngs.size(); i++) {
//                                    BitmapDescriptorFactory.fromResource(R.mipmap.icon_patrol_mark_znsb)
                                    String name = nameList.get(i);
                                    View view = View.inflate(context, R.layout.bubble_view, null);
                                    TextView textView = ((TextView) view.findViewById(R.id.title));
                                    textView.setText(name);
                                    MarkerOptions markerOptions = new MarkerOptions()
                                            .position(latLngs.get(i))
                                            .infoWindowEnable(false)
                                            .zIndex(MAP_INDEX)
                                            .icon(BitmapDescriptorFactory.fromView(view));
                                    Marker marker = aMap.addMarker(markerOptions);
                                    deviceMarker.add(marker);
                                }

                                if (latLngs.size() > 0 && deviceMarker == null) {
                                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLngs.get(0)));
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    /**
     * 实时的上报位置
     */
    private void uploadLocation(String lat, String lng, String updateTime) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("lat", lat);
        hashMap.put("lng", lng);
        hashMap.put("updateTime", updateTime);
        String str = GsonUtils.toJson(hashMap);

        OkGo.<String>post(Constant.getInstance().POST_UPLOAD_LOCATION)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e("uploadLocation error", "result===" + result);

                    }
                });
    }

    private ArrayList<LatLng> testList = new ArrayList<>();

    //轨迹纠偏的相关监听方法2
    @Override
    public void onTraceStatus(List<TraceLocation> locations, List<LatLng> rectifications, String errorInfo) {
        ToastUtils.showLong("轨迹纠偏中。。。。");
        try {
            if (!LBSTraceClient.TRACE_SUCCESS.equals(errorInfo)) {
                MyLogUtil.e("amap", " source count->" + (locations == null ? "0" : locations.size()) + "   result count->" + (rectifications == null ? "0" : rectifications.size()));

                StringBuffer stringBuffer = new StringBuffer();

                if (locations != null) {
                    for (TraceLocation location : locations) {
                        stringBuffer.append("{");
                        stringBuffer.append("\"lon\":").append(location.getLongitude()).append(",");
                        stringBuffer.append("\"lat\":").append(location.getLatitude()).append(",");
                        stringBuffer.append("\"loctime\":").append(location.getTime()).append(",");
                        stringBuffer.append("\"speed\":").append(location.getSpeed()).append(",");
                        stringBuffer.append("\"bearing\":").append(location.getBearing());
                        stringBuffer.append("}");
                        stringBuffer.append("\n");
                    }
                }
                MyLogUtil.e("amap", "轨迹纠偏失败，请先检查以下几点:\n" +
                        "定位是否成功\n" +
                        "onTraceStatus第一个参数中 经纬度、时间、速度和角度信息是否为空\n" +
                        "若仍不能解决问题，请将以下内容通过官网(lbs.amap.com)工单系统反馈给我们 \n" + errorInfo + " \n "
                        + stringBuffer.toString());


                return;
            }


            ToastUtils.showLong("rectifications size==" + rectifications.size());
            ToastUtils.showLong("locations size==" + locations.size());
            //======================
            for (int i = 0; i < rectifications.size(); i++) {
                LatLng latLng = rectifications.get(i);
                long time = locations.get(i).getTime();
                ToastUtils.showLong("111lat==" + latLng.latitude + ",lng==" + latLng.longitude);
                testList.add(latLng);
            }

            Polyline mapPolyline = aMap.addPolyline(new PolylineOptions()
                    .addAll(testList)
                    .width(Constant.POLYLINE_WIDTH)
                    .zIndex(MAP_INDEX)
                    .color(context.getResources().getColor(R.color.color_black)));

//                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(optimizeLatLng), 200));
            polylines.add(mapPolyline);


        } catch (Throwable e) {
            e.printStackTrace();
        }

    }


    /**
     * 判断我应用是否在白名单中
     *
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean isIgnoringBatteryOptimizations() {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
        }
        return isIgnoring;
    }

    /**
     * 不在白名单中申请加入白名单
     */

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void requestIgnoreBatteryOptimizations() {
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * ******************离线瓦片逻辑****************
     */
    private double[] getXYByLnglat(double lng, double lat, int level) {
        double n = Math.pow(2, level);
        double xtile = n * ((lng + 180) / 360);
        double lat_rad = lat / 360 * Math.PI * 2;
        double ytile = n * (1 - (Math.log(Math.tan(lat_rad) + 1 / Math.cos(lat_rad)) / Math.PI)) / 2;

        double XY[] = new double[2];
        XY[0] = xtile;
        XY[1] = ytile;

        return XY;
    }

    private double[] getLeftTop(int level) {
        return getXYByLnglat(LEFT_TOP_LOCATION[0], LEFT_TOP_LOCATION[1], level);
    }

    private double[] getRightBottom(int level) {
        return getXYByLnglat(RIGHT_BOTTOM_LOCATION[0], RIGHT_BOTTOM_LOCATION[1], level);
    }

    //切片的x,y,zoom值拼成的数组，用于切片请求时候的判断
    private void tileStr() {
        String XYZOOM = "";
        for (int zoom = MIN_ZOOM; zoom <= MAX_ZOOM; zoom++) {
            double[] leftTopXY = getLeftTop(zoom);
            double[] rightBottomXY = getRightBottom(zoom);
            for (int x = (int) leftTopXY[0]; x <= (int) rightBottomXY[0]; x++) {
                for (int y = (int) leftTopXY[1]; y <= (int) rightBottomXY[1]; y++) {
                    XYZOOM += zoom + "_" + x + "_" + y + ",";
                    if (zoom == MIN_ZOOM && x == (int) leftTopXY[0] && y == (int) leftTopXY[1]) {
                        SPStaticUtils.put(MySPTools.XYZOOM_LEFTTOP, zoom + "_" + x + "_" + y);
                    }
                    if (zoom == MAX_ZOOM && x == (int) rightBottomXY[0] && y == (int) rightBottomXY[1]) {
                        SPStaticUtils.put(MySPTools.XYZOOM_RIGHTBOTTOM, zoom + "_" + x + "_" + y);
                    }
                }
            }
        }
        SPStaticUtils.put(MySPTools.XYZOOM, XYZOOM);
    }

    /**
     * 下载瓦片
     *
     * @param url
     * @return
     */
    private void downMapTile(final String url, File file) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;
                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    try {
                        BufferedOutputStream bos = null;
                        try {
                            if (bitmap != null) {
                                file.getParentFile().mkdirs();
                                file.setWritable(true);
                                bos = new BufferedOutputStream(new FileOutputStream(file));
                                bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
                                bos.flush();
                                bos.close();
                            }

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }


    /**
     * 步骤1：创建AsyncTask子类
     * 注：
     * a. 继承AsyncTask类
     * b. 为3个泛型参数指定类型；若不使用，可用java.lang.Void类型代替
     * c. 根据需求，在AsyncTask子类内实现核心方法
     */

    private class TileTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            MyLogUtil.e("TileTask", "onPreExecute ====");
        }

        @Override
        protected Void doInBackground(Void... params) {
            tileStr();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            MyLogUtil.e("TileTask", "onPostExecute ====");
        }
    }


    /**
     * ******************地理围栏逻辑****************
     */
    private int mCustomID = 100;
    private Handler fenceHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    MyLogUtil.e(TAG, "添加围栏成功!!");
                    break;
                case 400:
                    MyLogUtil.e(TAG, "添加围栏失败!!");
                    break;
                case 500:
                    GeoFenceStatus = fenceHashMap.containsValue(true); //是否包含true
                    MyLogUtil.e(TAG, "GeoFenceStatus==" + GeoFenceStatus);
                    if (trackFlag && !GeoFenceStatus && Constant.getInstance().IS_OPEN_GEOFENCE) { //巡护进行中,离开围栏，结束巡护
                        strackEndEvent();
                        SPStaticUtils.put(SPTools.GeoFenceFlag, Constant.AUTO_END_TRACK_TYPE_TWO);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public void GeoFenceData() {

        OkGo.<String>get(Constant.getInstance().GET_TEST_FENCE)
                .tag(this)
                .params("toIndex", "-1")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            GeoFenceBean geoFenceBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                geoFenceBean = new GeoFenceBean();
                                geoFenceBean = gson.fromJson(result, GeoFenceBean.class);


                                List<GeoFenceBean.FeaturesBean> featuresBeans = geoFenceBean.getFeatures();
                                List<List<LatLng>> fenceLatLngList = new ArrayList<>(); //存放所有区域的数据

                                for (int i = 0; i < featuresBeans.size(); i++) {
                                    GeoFenceBean.FeaturesBean featuresBean = featuresBeans.get(i);
                                    List<List<List<Double>>> dataList = featuresBean.getGeometry().getCoordinates();
                                    List<List<Double>> pointList = dataList.get(0);
                                    List<LatLng> latLngs = new ArrayList<>();//存放单条区域的数据
                                    List<DPoint> points = new ArrayList<DPoint>();  //存放地里围栏需要的数据
                                    for (int j = 0; j < pointList.size(); j++) {
                                        List<Double> latLngList = pointList.get(j);
                                        double gpsLat = latLngList.get(1);
                                        double gpsLng = latLngList.get(0);
                                        //gps 转高德的经纬度
                                        double[] latlngs = GPSTransToAMap.transform(gpsLat, gpsLng);
                                        LatLng latLng = new LatLng(latlngs[0], latlngs[1]);
                                        latLngs.add(latLng); //将坐标装到数组里

                                        points.add(new DPoint(latlngs[0], latlngs[1]));
                                    }

                                    Polygon mapPolygon = aMap.addPolygon(new PolygonOptions()
                                            .addAll(latLngs)
                                            .fillColor(context.getResources().getColor(R.color.bg_color5))
                                            .strokeColor(context.getResources().getColor(R.color.blue_16b))
                                            .strokeWidth(1));
                                    fencePolygonList.add(mapPolygon);
                                    fenceLatLngList.add(latLngs);

                                    mGeoFenceClient.addGeoFence(points, mCustomID + i + "");

                                }

//                                if (fenceLatLngList.size() > 0) {
//                                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(fenceLatLngList.get(0)), 200));
//                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    /**
     * 初始化地理围栏设置
     */
    public void initAMapGeoFence() {
        IntentFilter fliter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        fliter.addAction(GEOFENCE_BROADCAST_ACTION);
        registerReceiver(mGeoFenceReceiver, fliter);

        mGeoFenceClient = new GeoFenceClient(this);
        //暂时隐藏地理围栏监听
        mGeoFenceClient.setGeoFenceListener(this);
        mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);
        mGeoFenceClient.setActivateAction(GeoFenceClient.GEOFENCE_IN | GeoFenceClient.GEOFENCE_STAYED | GeoFenceClient.GEOFENCE_OUT);

    }


    @Override
    public void onGeoFenceCreateFinished(List<GeoFence> geoFenceList, int errorCode, String s) {
        if (errorCode == GeoFence.ADDGEOFENCE_SUCCESS) {//判断围栏是否创建成功
            //geoFenceList是已经添加的围栏列表，可据此查看创建的围栏
            Message message = mHandler.obtainMessage();
            message.obj = geoFenceList;
            message.what = 200;
            fenceHandler.sendMessage(message);
        } else {

            Message msg = Message.obtain();
            msg.arg1 = errorCode;
            msg.what = 400;
            fenceHandler.sendMessage(msg);
        }
    }

    //存储定位点是否在围栏里的状态，在存true,不在存false
    private HashMap<String, Boolean> fenceHashMap = new HashMap<>();
    private BroadcastReceiver mGeoFenceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //生命周期只有十秒左右，如果在 onReceive() 内做超过十秒内的事情，就会报ANR(Application No Response) 程序无响应的错误信息
            // 接收广播
            if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
                Bundle bundle = intent.getExtras();
                //获取当前有触发的围栏对象：
                GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
                //获取自定义的围栏标识：
                String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
                //获取围栏ID:
                String fenceID = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
                //获取围栏行为：
                int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
                int code = bundle.getInt(GeoFence.BUNDLE_KEY_LOCERRORCODE);
                StringBuffer sb = new StringBuffer();
                switch (status) {
                    case GeoFence.STATUS_LOCFAIL:
                        sb.append("定位失败,code=").append(code);
                        break;
                    case GeoFence.STATUS_IN:
                        sb.append("进入围栏,fenceID=").append(fenceID);
                        fenceHashMap.put(fenceID, true);
                        break;
                    case GeoFence.STATUS_OUT:
                        sb.append("离开围栏,fenceID=").append(fenceID);
                        fenceHashMap.put(fenceID, false);
                        break;
                    case GeoFence.STATUS_STAYED:
                        sb.append("停留在围栏内,fenceID=").append(fenceID);
                        break;
                    default:
                        break;
                }
                String str = sb.toString();
                MyLogUtil.e(TAG, str);
//                ToastUtils.showLong(str);
                Message msg = Message.obtain();
                msg.obj = str;
                msg.what = 500;
                fenceHandler.sendMessage(msg);
            }
        }
    };


    /**
     * 获取用户信息
     */
    private void getUserInfo(ResultCallback resultCallback) {

        OkGo.<String>get(Constant.getInstance().GET_USER_INFO)
                .tag(this)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                UserInfoBean userInfoBean = new UserInfoBean();
                                userInfoBean = gson.fromJson(result, UserInfoBean.class);

                                UserInfoBean.UserBean userBean = userInfoBean.getUser();
                                String userId = userBean.getUserId();

                                if (!StringUtils.isEmpty(userId)) {
                                    SPStaticUtils.put(SPTools.userId, userId);//保存userId
                                    resultCallback.result(true);
                                } else {
                                    resultCallback.result(false);
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                    }
                });


    }


    /*******************************离线加载逻辑***********************/
    public void reloadMap() {
        aMap.setLoadOfflineData(true);
        aMap.reloadMap();
    }

    @Override
    public void onNetChange(boolean netWorkState) {
        super.onNetChange(netWorkState);
        this.netWorkState = netWorkState;
        locationCity = SPStaticUtils.getString(SPTools.city);
        if (!StringUtils.isEmpty(locationCity)) {
            initOfflineMap();
        }
    }


    @Override
    public void onVerifyComplete() {
        MyLogUtil.e("offline", "onVerifyComplete===");
        haveLocationOfflineMap(offlineMapManager, locationCity, new ResultCallback() {
            @Override
            public void result(Object object) {
                MyLogUtil.e("offline", "haveLocationOfflineMap===" + object + ",netWorkState==" + netWorkState);
                if (Boolean.parseBoolean(object.toString())) {
                    //存在当前定位城市的离线地图
                    if (!netWorkState) {
                        tvTopTip2.setVisibility(View.VISIBLE);
                        tvTopTip2.setText(tipArray[0]);
                    } else {
                        tvTopTip2.setVisibility(View.GONE);
                    }

                } else {
                    tvTopTip2.setVisibility(View.GONE);
                    //不存在当前定位城市的离线地图
                    String token = SPStaticUtils.getString(SPTools.token);
                    if (!netWorkState && !StringUtils.isEmpty(token)) {
                        //弹出dialog  引导用户进入离线地图下载界面
                        netPopupView = new XPopup.Builder(ActivityUtil.getTopActivity())
                                .isDestroyOnDismiss(true)
                                .dismissOnTouchOutside(true)
                                .hasShadowBg(true)
                                .asConfirm(context.getResources().getString(R.string.text_tip), "网络不佳，恢复网络后请下载离线地图，体验更好哦~",
                                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),

                                        new OnConfirmListener() {
                                            @Override
                                            public void onConfirm() {
                                                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), MyOffLineMapActivity.class);
                                            }
                                        }, null, false)
                                .show();
                    }

                    if (netWorkState) {
                        if (netPopupView != null) {
                            if (netPopupView.isShow()) netPopupView.dismiss();
                        }
                    }
                }
            }
        });
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //当用户处在次页面的时候，联网之后刷新数据
        String message = event.getMessgae();
        if (message.equals(Constant.INIT_OFF_LINE_MAP)) {
            MyLogUtil.e("onStringEvent", "onStringEvent===");
            initOfflineMap();
        }


    }


    /*******************************定位精度圈***********************/

    private Marker addMarker(LatLng point) {
        Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                R.mipmap.gps_point);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);
        Marker marker = aMap.addMarker(new MarkerOptions().position(point).icon(des)
                .anchor(0.5f, 0.5f));
        return marker;
    }

    private void addLocationMarker(AMapLocation aMapLocation) {
        LatLng mylocation = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        float accuracy = aMapLocation.getAccuracy();
        if (locMarker == null) {
            locMarker = addMarker(mylocation);
            ac = aMap.addCircle(new CircleOptions().center(mylocation)
                    .fillColor(Color.argb(100, 255, 218, 185)).radius(accuracy)
                    .strokeColor(Color.argb(255, 255, 228, 185)).strokeWidth(5));
            c = aMap.addCircle(new CircleOptions().center(mylocation)
                    .fillColor(Color.argb(70, 255, 218, 185))
                    .radius(accuracy).strokeColor(Color.argb(255, 255, 228, 185))
                    .strokeWidth(0));
        } else {
            locMarker.setPosition(mylocation);
            ac.setCenter(mylocation);
            ac.setRadius(accuracy);
            c.setCenter(mylocation);
            c.setRadius(accuracy);
        }
        Scalecircle(c);
    }


    public void Scalecircle(final Circle circle) {
        start = SystemClock.uptimeMillis();
        mTimerTask = new circleTask(circle, 1000);
        mTimer.schedule(mTimerTask, 0, 30);
    }

    private final Interpolator interpolator1 = new LinearInterpolator();

    private class circleTask extends TimerTask {
        private double r;
        private Circle circle;
        private long duration = 1000;

        public circleTask(Circle circle, long rate) {
            this.circle = circle;
            this.r = circle.getRadius();
            if (rate > 0) {
                this.duration = rate;
            }
        }

        @Override
        public void run() {
            try {
                long elapsed = SystemClock.uptimeMillis() - start;
                float input = (float) elapsed / duration;
//                外圈循环缩放
//                float t = interpolator.getInterpolation((float)(input-0.25));//return (float)(Math.sin(2 * mCycles * Math.PI * input))
//                double r1 = (t + 2) * r;
//                外圈放大后消失
                float t = interpolator1.getInterpolation(input);
                double r1 = (t + 1) * r;
                circle.setRadius(r1);
                if (input > 2) {
                    start = SystemClock.uptimeMillis();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    /*******************************锁屏操作***********************/
    public void addScreenChangeBroadCast() {
        if (mScreenBroadcastReceiver == null) {
            mScreenBroadcastReceiver = new BroadcastReceiver() {
                @SuppressLint("InvalidWakeLockTag")
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (action != null && action.length() > 0) {
                        switch (action) {
                            //当屏幕灭了
                            case Intent.ACTION_SCREEN_OFF:
//                                try {
//                                    PowerManager powerManager = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
//                                    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyTag"); //保持CPU 运转，屏幕和键盘灯有可能是关闭的
//                                    wakeLock.acquire();
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
                                break;
                            //当屏幕亮了
                            case Intent.ACTION_SCREEN_ON:
                                //加载慢
                                //跳转添加标记
//                                Intent i = new Intent(context, LockScreenActivity.class);
//                                i.setPackage(AppUtils.getAppPackageName());
//                                i.setAction("com.android.lockscreen");
//                                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//                                startActivity(i);

                                //关闭系统锁屏 有无法重启锁屏的bug
//                                try {
//                                    KeyguardManager keyguardManager = (KeyguardManager) getActivity().getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
//                                    KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("");
//                                    keyguardLock.disableKeyguard();
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }

//                                if (wakeLock != null) {
//                                    wakeLock.release();
//                                }

                                String distance = UIUtils.getTextView(tvMileage);
                                SPStaticUtils.put(SPTools.distance, distance);
                                //系统不会重复创建锁屏页，所以这里不用做相关判断
                                Intent i = new Intent(ActivityUtil.getTopActivity(), LockScreenNewActivity.class);
                                i.setPackage(AppUtils.getAppPackageName());
                                i.setAction("com.android.lockscreen");
                                i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                                        | Intent.FLAG_FROM_BACKGROUND
                                        | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
                                        | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
                                        | Intent.FLAG_ACTIVITY_NO_ANIMATION
                                        | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
                                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                                PendingIntent pendingIntent =
                                        PendingIntent.getActivity(context, 0, i, 0);

                                try {
                                    pendingIntent.send();
                                } catch (PendingIntent.CanceledException e) {
                                    e.printStackTrace();
                                }

                                break;
                            default:
                                break;
                        }
                    }

                }
            };
            //锁屏
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            try {
                registerReceiver(mScreenBroadcastReceiver, filter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void removeScreenChangeBroadCast() {
        MyLogUtil.e("lockscreen", "removeScreenChangeBroadCast======");
        if (mScreenBroadcastReceiver != null) {
            try {
                unregisterReceiver(mScreenBroadcastReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mScreenBroadcastReceiver = null;
        }
    }


    /*******************************传感器***********************/
    private class MySensorEventListener implements SensorEventListener {

        @Override
        public void onSensorChanged(SensorEvent event) {
//            MyLogUtil.e("sensorManager", "onSensorChanged====\n" + event.values[0] + "\n,1 ==" + event.values[1] + "\n,2==" + event.values[2]);
            if (event == null || event.values == null || event.values.length <= 0) {
                isSports = false;
                return;
            }
            float xValue = event.values[0];
            float yValue = event.values[1];
            float zValue = event.values[2];
            List<Float> sensorValues = new ArrayList<>();
            sensorValues.add(Math.abs(xValue));
            sensorValues.add(Math.abs(yValue));
            sensorValues.add(Math.abs(zValue));
            maxSensorValue = Collections.max(sensorValues);

            if (Math.abs(xValue) > 1 || Math.abs(yValue) > 1 || Math.abs(zValue) > 1) { // x 、y、z y有任何一个方向的加速度的绝对值超过1， 说明设备在运动
                isSports = true;
            } else {
                isSports = false;
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {

        }
    }

}